<template>
  <div class="userList">
    <md-table
      v-model="searched"
      md-sort="name"
      md-sort-order="asc"
      md-fixed-header
      @md-selected="onSelect"
    >
      <!-- 搜索、按钮 -->
      <md-table-toolbar>
        <md-field md-clearable class="search md-toolbar-section-start">
          <md-input
            placeholder="输入书名查找..."
            v-model="selectedBook"
            @input="searchOnTable"
          />
        </md-field>
        <div md-clearable class="search md-toolbar-section-end">
          <md-button
            @click="createNewBook"
            class="md-dense md-raised md-primary"
            >新增</md-button
          >
          <md-button
            :disabled="selected.length === 0"
            @click="batchDel"
            class="md-dense md-raised md-accent"
            >批量删除</md-button
          >
        </div>
      </md-table-toolbar>
      <!-- 选中提示 -->
      <md-table-toolbar slot="md-table-alternate-header" slot-scope="{ count }">
        <div class="md-toolbar-section-start">
          {{ getAlternateLabel(count) }}
        </div>
        <div class="md-toolbar-section-end">
          <md-button class="md-icon-button">
            <md-icon class="fa fa-trash"></md-icon>
          </md-button>
        </div>
      </md-table-toolbar>
      <!-- 表格空 -->
      <md-table-empty-state
        md-label="没有找到图书"
        :md-description="`没有找到含有书名为 '${selectedBook}' 的图书.`"
      >
      </md-table-empty-state>
      <!-- 表格 -->
      <md-table-row
        slot="md-table-row"
        slot-scope="{ item, index }"
        md-selectable="multiple"
      >
        <md-table-cell md-label="序号" md-numeric>
          {{ index }}
        </md-table-cell>
        <md-table-cell md-label="书名" md-sort-by="name">
          {{ item.name }}
        </md-table-cell>
        <md-table-cell md-label="作者" md-sort-by="author">
          {{ item.author }}
        </md-table-cell>
        <md-table-cell md-label="出版日期" md-sort-by="publishAt">
          {{ item.publishAt }}
        </md-table-cell>
        <md-table-cell md-label="操作">
          <md-button
            @click="del(item.id)"
            class="md-mini md-icon-button md-dense md-primary"
          >
            <span style="font-size: 16px; color: Dodgerblue">
              <i class="fas fa-trash-alt"></i>
            </span>
          </md-button>
          <md-button
            @click="edit(item.id)"
            class="md-icon-button md-dense md-primary"
          >
            <span style="font-size: 16px; color: Tomato">
              <i class="fas fa-edit"></i>
            </span>
          </md-button>
        </md-table-cell>
      </md-table-row>
    </md-table>
    <p>
      <vxe-pager
        @page-change="pageChange"
        background
        :current-page.sync="pager.page"
        :page-size.sync="pager.limit"
        :total="pager.total"
        :layouts="[
          'PrevJump',
          'PrevPage',
          'JumpNumber',
          'NextPage',
          'NextJump',
          'Sizes',
          'FullJump',
          'Total'
        ]"
      >
      </vxe-pager>
    </p>
    <!-- 跳转登录弹出框 -->
    <md-dialog-confirm
      :md-active.sync="showJumpAlert"
      md-title="跳转提示"
      :md-content="`登录失效，${seconds}秒后将跳转到登录页`"
      md-cancel-text="取消"
      md-confirm-text="去登录"
      @md-cancel="cancelJumpToLogin"
      @md-confirm="jumpToLogin"
    />
    <!-- 新增、编辑弹出框 -->
    <md-dialog :md-active.sync="showEditDialog">
      <md-dialog-title>{{ dialogTitle }}</md-dialog-title>
      <md-content>
        <form ref="form11">
          <md-field md-clearable>
            <label>书名</label>
            <md-input v-model="newbook.name" md-counter="20"></md-input>
          </md-field>
          <md-field md-clearable>
            <label>作者</label>
            <md-input v-model="newbook.author" maxlength="10"></md-input>
          </md-field>
          <p class="md-subheading">出版日期</p>
          <md-datepicker v-model="newbook.publishAt" md-immediately />
          <md-field md-clearable>
            <label>简介</label>
            <md-textarea
              v-model="newbook.description"
              md-counter="200"
            ></md-textarea>
          </md-field>
        </form>
      </md-content>
      <md-dialog-actions>
        <md-button @click="showEditDialog = false">取消</md-button>
        <md-button class="md-primary" @click="addNewBook">保存</md-button>
      </md-dialog-actions>
    </md-dialog>
    <!-- 删除提示弹出框 -->
    <md-dialog-confirm
      :md-active.sync="showDelAlert"
      md-title="提示"
      md-content="您确定要删除吗"
      md-confirm-text="删除"
      md-cancel-text="取消"
      @md-confirm="confirmDel"
    />
    <md-snackbar
      md-position="center"
      :md-active.sync="showSnackbar"
      md-persistent
    >
      <span>{{ message }}</span>
      <md-button
class="md-primary"
@click="showSnackbar = false"
        >关闭</md-button
      >
    </md-snackbar>
  </div>
</template>
<script>
import API from '@/api/api_book.js'
import { mapState } from 'vuex'
// import Tool from '@/utils/tools'
import { logTimeOut } from '@/mixin'
import format from 'date-fns/format'
export default {
  data() {
    return {
      searched: [],
      selectedBook: '',
      currentId: [],
      selected: [],
      showSnackbar: false,
      newbook: {
        author: '',
        name: '',
        publishAt: format(new Date(), 'yyyy-MM-dd'),
        description: ''
      },
      message: '',
      showDelAlert: false,
      showEditDialog: false,
      dialogTitle: '新增用户',
      pager: {
        page: 1,
        limit: 10,
        total: 0
      }
    }
  },
  mixins: [logTimeOut],
  computed: {
    ...mapState(['sessionInvalid'])
  },
  methods: {
    getBooks() {
      const _this = this
      const params = {
        page: this.pager.page,
        limit: this.pager.limit,
        name: this.selectedBook
      }
      API.findList(params).then(res => {
        if (this.sessionInvalid) {
          // 登陆超时
          _this.handleLoginTimeOut()
        } else {
          this.pager.total = res.total
          this.pager.limit = res.limit
          console.log(res.books)
          _this.searched = res.books
        }
      })
    },
    // 确定删除
    confirmDel() {
      if (this.selected.length) {
        const ids = this.currentId.join(',')
        API.batchDelBooks(ids).then(res => {
          if (res && parseInt(res.errcode) === 0) {
            this.showSnackbar = true
            this.message = '批量删除成功'
            this.getBooks()
            this.currentId = []
          }
        })
      } else {
        API.delBook(this.currentId[0]).then(res => {
          if (res && parseInt(res.errcode) === 0) {
            this.showSnackbar = true
            this.message = '删除成功'
            this.getBooks()
            this.currentId = []
          }
        })
      }
    },
    // 批量删除
    batchDel() {
      for (const item of this.selected) {
        this.currentId.push(item.id)
      }
      this.showDelAlert = true
    },
    del(id) {
      this.currentId.push(id)
      this.showDelAlert = true
    },
    edit(id) {
      this.dialogTitle = '编辑图书'
      this.showEditDialog = true
      API.getBook(id).then(res => {
        this.newbook.name = res.name
        this.newbook.author = res.author
        this.newbook.description = res.description
        this.newbook.publishAt = res.publishAt
      })
    },
    createNewBook() {
      this.resetForm()
      this.dialogTitle = '新增图书'
      this.showEditDialog = true
    },
    // 新增
    addNewBook() {
      for (const key in this.newbook) {
        if (this.newbook[key] === '') {
          this.showSnackbar = true
          this.message = '内容填写不完整，请重新添加'
          return
        }
      }
      this.newbook.publishAt = format(this.newbook.publishAt, 'yyyy-MM-dd')
      const params = this.newbook
      console.log(params)
      API.addBook(params).then(res => {
        this.showSnackbar = true
        this.message = '添加成功'
        this.showEditDialog = false
        this.resetForm()
        this.getBooks()
      })
    },
    resetForm() {
      this.newbook = {
        author: '',
        name: '',
        publishAt: new Date(),
        description: ''
      }
    },
    onSelect(items) {
      this.selected = items
    },
    getAlternateLabel(count) {
      return `已选中${count}本书`
    },
    searchOnTable() {
      this.getBooks()
    },
    pageChange(info) {
      this.page = info.currentPage
      this.getBooks()
    }
  },
  mounted() {
    this.getBooks()
  },
  beforeRouteLeave(to, from, next) {
    this.cancelJumpToLogin()
    next()
  }
}
</script>

<style lang="less" scope>
.search {
  max-width: 500px;
  margin-bottom: 10px;
}
.md-dialog-container {
  width: 450px;
  .md-content {
    padding: 0 30px;
  }
}

.md-empty-state {
  display: inline-block;
  vertical-align: middle;

  + .md-empty-state {
    margin-left: 16px;
  }
  .md-empty-state-description {
    color: #aaa;
  }
}
</style>
